package com.kk.loadtext;

import com.kk.utils.AdvanceThreadPool;
import org.json.simple.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Objects;

/**
 * @author 王志强
 * @date 2021-12-02
 * description: 长连接传输数据
 */
public class Server {
    private final Logger logger = LoggerFactory.getLogger(Server.class);
    private ServerSocket serverSocket;
    private Socket socket;

    public Server() {
        try {
            serverSocket = new ServerSocket(8888);
            while (true) {
                logger.debug("服务端等待连接。。。");
                socket = serverSocket.accept();
                if (Objects.nonNull(socket)) {
                    logger.info("{} 已连接\n", socket);
                    AdvanceThreadPool.poolExecutor.submit(new ServerRead());
                }
            }

        } catch (IOException e) {
            logger.error(e.getMessage());
        }
    }


    public static void main(String[] args) {
        Server server = new Server();
    }


    /**
     * 专用于服务端接收数据
     */
    class ServerRead implements Runnable {
        @Override
        public void run() {
            try {
                ObjectInputStream inputStream = new ObjectInputStream(socket.getInputStream());
                while (true) {
                    JSONObject readObject = (JSONObject) inputStream.readObject();
                    logger.info("receive data is {}", readObject);
                }
            } catch (IOException | ClassNotFoundException e) {
                logger.error("Disconnect or ClassNotFoundException！！");
            } finally {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
